
<template>
    <div class="ingr-comp-target-comp" ref="ingrTarg">
         <TitleBox type=2>
            <template #titlecont>
                <span v-lang="{lang: controlSto.language, lgid: -22}">Target</span>
            </template>
        </TitleBox>
        <!-- TODO 1个echart -->
        <div class="chart-box">
            <div class="chart-img-wrap">
                <uiEchart :config="optionChart" :vt="dataObj.echartoptVt1" ref="chartCompTarget"/>
            </div>
        </div>

        <div class="condition-box">
            <div class="condition-left">
                <SearchDrop class="cond-item">
                    <template #title>
                        <span v-lang="{lang: controlSto.language, lgid: -44}">List sort</span>
                    </template>
                    <template #dropcont>
                        <div class="cond-drop-cont-wrap">
                            <el-radio-group v-model="condObj.sort"  @change="toSearch">
                                <div class="cond-radio-wrap">
                                    <el-radio class="cond-radio-item" value="Asc"><span v-lang="{lang: controlSto.language, lgid: -49}"></span></el-radio>
                                    <el-radio class="cond-radio-item" value="Desc"><span v-lang="{lang: controlSto.language, lgid: -50}"></span></el-radio>
                                </div>
                            </el-radio-group>
                        </div>
                    </template>
                </SearchDrop>
                <SearchDrop class="cond-item">
                    <template #title>
                        <span v-lang="{lang: controlSto.language, lgid: -45}">Type</span>
                        <!-- <el-popover placement="top-start">
                            <el-checkbox class="all-choose-cls"
                                v-model="condObj.TypeAll"
                                @change="allChooseType"
                            >
                            <span @click.stop="condObj.TypeAll = !condObj.TypeAll" v-lang="{lang: controlSto.language, lgid: -130}">select all</span>
                        </el-checkbox>
                            <template #reference>
                                <span v-lang="{lang: controlSto.language, lgid: -45}">Type</span>
                            </template>
                        </el-popover> -->
                    </template>
                    <template #dropcont>
                        <div class="cond-drop-cont-wrap">
                            <el-checkbox class="all-choose-cls"
                                v-model="condObj.TypeAll"
                                @change="allChooseType"
                            >
                            <span @click.stop="condObj.TypeAll = !condObj.TypeAll" v-lang="{lang: controlSto.language, lgid: -130}">select all</span>
                        </el-checkbox>
                            <el-checkbox-group v-model="condObj.typeList" @change="toSearch">
                                <div class="cond-chbox-wrap">
                                    <el-checkbox class="cond-chbox-item" v-for="item in dataObj.typeList" :key="'type_' + item.id" :value="item.typeCode" :label="item.typeName" />
                                </div>
                            </el-checkbox-group>
                        </div>
                    </template>
                </SearchDrop>
            </div>
            <div class="condition-right">
                <div class="ipt-cont">
                    <el-input class="ipt-search" clearable="true" v-model="condObj.searchword" autofocus :placeholder="searchPlace" />
                </div>
                <SearchBtn class="search-item" @click.stop="toSearch"/>

                <TableFilter class="search-item" :column="dataObj.columnList" :filterKey="condObj.filterKey" @onChg="chgTableCol"/>

                <SearchLoad type='ingreCompTarget' :uiCode="condObj.uiCode" :para="{
                    'content': condObj.searchword,
                    'langCode': controlSto.language == 1 ? 'ENG' : 'CHN',
                    'uiTypeCode':condObj.uiCode,
                    'type': condObj.typeList.join(','),
                    'ingrId': detailId,
                    'sortType': condObj.sort
                }"/>
            </div>
        </div>


        <div class="cont-box">
            <uiTable
                :config="dataObj.tableConfig"
                :columnConfig="dataObj.columnConfig" 
                :data="dataObj.dataList"
                :loading="isLoading"
                :key="dataObj.searchTablevt">
            </uiTable>
            <div class="page-box" v-if="condObj.total > 10">
                <uiPagination
                    :total="condObj.total" :pageSize="condObj.pageSize" :pageIndex="condObj.pageIndex"
                    @onSizeChange="chgSize" @onCurrentChange="chgCurrnt"/>
            </div>
        </div>
    </div>
</template>

<script setup>
    import { ref, reactive, toRefs, computed, onBeforeMount, watch } from 'vue';
    import { useIntersectionObserver } from '@vueuse/core';
    import TitleBox from '@/components/TitleBox.vue'
    import SearchBtn from '@/components/SearchBtn.vue'
    import uiEchart from '@/components/ui-echart.vue'
    import TableFilter from '@/components/TableFilter.vue'
    import SearchLoad from '@/components/SearchLoad.vue'
    import uiTable from '@/components/ui-table.vue'
    import uiPagination from '@/components/ui-pagination.vue'

    import { langTxt, getFilterThArr, getFilterLangArr, computedgraphOptions } from '@/utils/util'
    import { getTableThList, getIngredientCompTarget, getTargetType, getIngredientTargetStatistic } from '@/service/tcm'
    import { typeList } from '@/utils/database'

    import { controlStore } from '@/stores/control'
    import { debounce } from 'lodash'
    
    const emitter = defineEmits(['toCalc']);
    const ingrTarg = ref(null);
    const controlSto = controlStore();
    const props = defineProps({
        detailId: {
            type: [Number, String],
            default: ''
        }
    });
    const { detailId } = toRefs(props);
    
    let searchDebounce = null;
    const chartCompTarget = ref(null);
    const optionChart = computedgraphOptions(langTxt(controlSto.language, '-107'), '', [], true, 'center', '70%', ['50%', '50%'])

    
    const isLoading = ref(true);

    const condObj = reactive({
		searchword: '',
		filterKey: 'ingr3',
        uiCode: 'ingredient_composition_target',
        word: '',
        total: 0,
        pageSize: 10,
        pageIndex: 1,
        type: [],
        sort: 'Asc',
        typeList: [],
        TypeAll: true
	});

	const dataObj = reactive({
		searchTablevt: 1,
		echartoptVt1: 1,
		columnList: [],
		tableConfig: {
			// size: 'small',
			'tooltip-effect': 'dark',
			'highlight-current-row': true,
			stripe: true,
			'header-cell-style': { background: '#BC9F77', color: '#FFF' },
		},
		columnConfig: [],
		dataList: [],
        typeList: []
	});

    const searchPlace = computed(() => {
		return langTxt(controlSto.language, '-15');
	});

    onBeforeMount(()=> {
        getTableTh();
        toGetTargetType();
        // const {stop} = useIntersectionObserver(
        //     ingrTarg,
        //     ([{ isIntersecting }], observerElement) => {
        //         if (isIntersecting) {
        //             // 停止监听，如果你只想知道一次可视性变化
        //             // initDebounce();
        //             getTableTh();
        //             // toGetData();
        //             toGetTargetType();
        //             //阻止再次请求
        //             stop()
        //         }
        //     },
        //     {
        //         threshold: 0, // 当交叉框达到视窗的这部分时触发
        //     }
        // );
    });

    const initDebounce = () => {
        searchDebounce = debounce((e) => {
           getDataList();
        }, 1000);
    };
     // TODO
     const toGetTargetType = () => {
        getTargetType({langCode: controlSto.language == 1 ? 'ENG' : 'CHN'}).then(res => {
            if (res.success && res.data) {
                dataObj.typeList = res.data;
                res.data.forEach(e => {
                    condObj.typeList.push(e.typeCode)
                })
                condObj.typeList = [...new Set(condObj.typeList)]
                toIngreComTargetStatistic();
                getDataList();
            }
        })
    }
    const toIngreComTargetStatistic = () => {
        getIngredientTargetStatistic({ingrId: detailId.value}).then(res => {
            if (res.success) {
                if (res.data) {
                    let statisticData = [];
                    for(const key in res.data) {
                        dataObj.typeList.forEach(e => {
                            if(e.typeCode == key) {
                                statisticData.push({
                                    name: e.typeName,
                                    value: res.data[key],
                                    typeCode: e.typeCode
                                })
                            }
                        })
                    }
                    optionChart.series[0].data = statisticData;
                    optionChart.title.text = langTxt(controlSto.language, '-107');
                    optionChart.toolbox.feature.saveAsImage.title = controlSto.language == 1 ? 'Download' : '下载';
                    statisticData.length < 5 ? optionChart.legend.top = 'center' : ''
                    chartCompTarget.value.initEchart();
                }
            }
        })
    }
    const getTableTh = () => {
        let params = {
            uiCode: condObj.uiCode,
            langCode: 'ENG,CHN'
        };
        
        getTableThList(params).then((res) => {
            // isLoading.value = false;
            if (res.success) {
                let arr = res.data || [];
                let thArr = getFilterThArr(arr, dataObj.filterKey);
        		let langArr = getFilterLangArr(thArr);
        		controlSto.setLangList(langArr);
        		dataObj.columnList = thArr;
            }
        }).catch(() => {});


        // let thArr = getFilterThArr(arr, condObj.filterKey);
        // let langArr = getFilterLangArr(thArr);
        // controlSto.setLangList(langArr);
        // dataObj.columnList = thArr;
    };

    const chgTableCol = (e) => {
		dataObj.columnConfig = e || [];
		dataObj.searchTablevt = new Date().valueOf();
        emitter('toCalc');
    };

    
    const toGetData = () => {
        searchDebounce && searchDebounce();
    };

    const getDataList = () => {
        let params = {
            langCode: controlSto.language == 1 ? 'ENG' : 'CHN',
            ingrId: detailId.value,
            content: condObj.word,
            uiTypeCode: condObj.uiCode,
			pageNo: condObj.pageIndex || 10,
			pageSize: condObj.pageSize || 1,
            sortType: condObj.sort,
            type: condObj.typeList.join(',')
        };
        isLoading.value = true;
        getIngredientCompTarget(params).then((res) => {
            isLoading.value = false;
            if (res.success && res.data && res.data.records) {
                dataObj.dataList = res.data.records || [];
                condObj.total = res.data.totalCount || 0;
            }
        }).catch(() => {
            isLoading.value = false;
        });

        emitter('toCalc');
    };
    const allChooseType = () => {
		if(condObj.typeList.length == dataObj.typeList.length) {
			condObj.typeList = [];
		} else {
			condObj.typeList = [];
			dataObj.typeList.forEach(e => {
				condObj.typeList.push(e.typeCode)
			})
		}
	}

        
    const chgSize = (e) => {
        condObj.pageSize = e || 10;
        getDataList();
    };
    const chgCurrnt = (e) => {
        condObj.pageIndex = e || 1;
        getDataList();
    };
    const toSearch = () => {
        condObj.word = condObj.searchword;
        condObj.pageIndex = 1;
        getDataList();
    };
    
    watch(() => controlSto.language, (n, v) => {
        if(n != v && v) {
            // toGetData();
            toGetTargetType();
        }
    }, { immediate: true });
    watch(() => condObj.typeList, (n, v) => {
		if(n != v) {
			toSearch();
			if(n.length == dataObj.typeList.length) condObj.TypeAll = true;
			else condObj.TypeAll = false;
		}
	})

</script>


<style lang="scss" scoped>
    .ingr-comp-target-comp {
        .chart-box {
            display: flex;
            justify-content: center;
            padding: 24px 0 0;
            .chart-img-wrap {
                height: 240px;
                width: 50%;
                max-width: 500px;
                padding: 8px 12px 0;
            }
        }
        .condition-box {
            display: flex;
            padding: 30px 0;
            justify-content: space-between;
            .condition-left {
                .cond-item {
                    margin-right: 16px;
                }
            }
            .condition-right {
                .ipt-cont {
                    display: inline-block;
                    padding-right: 16px;
                    .ipt-search {
                        // width: 300px;
                    }
                }
                .search-item {
                    margin-right: 16px;
                }
            }
        }
        .cont-box {
            .page-box {
                padding: 10px 0;
            }
        }
    }
</style>
